package com.example.springsecurity03.config;

import com.example.springsecurity03.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @Author:
 * @DATE:2023/7/4 10:35
 * @Description:
 * @Version 1.0
 */

@Configuration
public class SecurityConfigure extends WebSecurityConfigurerAdapter {
     //数据库实现
    @Autowired
     private MyUserDetailService myUserDetailService;



//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager inMemoryUserDetailsManager=new InMemoryUserDetailsManager();
//        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin").build());
//        return inMemoryUserDetailsManager;
//    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
           http.authorizeRequests()
                   .mvcMatchers("/login.html").permitAll()
                   .anyRequest().authenticated()
                   .and()
                   .formLogin()
                   .loginPage("/login.html")
                   .loginProcessingUrl("/doLogin")
                   .usernameParameter("uname")
                   .passwordParameter("passwd")
                   .defaultSuccessUrl("/index.html",true)
                   .failureUrl("/login.html")
                   .and()
                   .logout()
                   .logoutUrl("/logout")
                   .logoutSuccessUrl("/login.html")
                   .and()
                   .cors().disable();
     }
}
